import React  from 'react';
// 浅拷贝 深拷贝 
class App extends React.Component{
  
  componentDidMount() {
    //浅拷贝
    console.log("====================浅Copy====================")
    this.qianCopy();
    // ... 拷贝
    console.log("====================...Copy====================")
    this.dianCopy()

    //JSON.parse(JSON.stringify())方式 方式拷贝 
    console.log("====================jsonCopy====================")
    this.jsonCopy()

    console.log("====================递归Copy====================")
    this.shenCopy()

  }

  //浅拷贝, 在react 中 所有状态修改都不能直接修改原来的转态值 
  qianCopy(){
    const obj1 = {a: '111', b: '222'}
    const obj2 = obj1
    obj2.c = '333'
    console.log(obj1) // {a: '111', b: '222', c: '333'}
  }
  //... 点方式拷贝 只会拷贝对象中的第一层属性 ,arr仍只是拷贝了引用，还是浅拷贝
  dianCopy(){
    const obj1 = {a: '111', arr: [1,2,3]}
    const obj2 = {...obj1} // 或者Object.assign(obj2, obj1)
    obj2.arr.push(4)
    console.log(obj1) // {a: '111', arr: [1,2,3,4]}
  }
  
  // JSON.parse(JSON.stringify())方式，缺点：无法复制function，或不适应存在属性值为undefined的对象或，无法适用全部场景
  jsonCopy(){
    const obj1 = {a: '111', arr: [1,2,3],c:undefined}
    const obj2 = JSON.parse(JSON.stringify(obj1))
    obj2.arr.push(4)
    console.log(obj1) // {a: '111', arr: [1,2,3,4],c:undefined}
    console.log(obj2) //{a: "111", arr: Array(4)}    丢失 c:undefined
  }

  shenCopy(){
   const obj1 = {a: '111', arr: [1,2,3],c:undefined}
   const obj2 = this.deepCopy(obj1)
    obj2.arr.push(4)
    console.log(obj1) // {a: '111', arr: [1,2,3,4],c:undefined}
    console.log(obj2) //{a: "111", arr: Array(4)}    丢失 c:undefined
  }


  // deepCopy深克隆 ,递归一层层赋值，缺点：性能不好，占内存
  deepCopy(value) {
    if(value instanceof Function){
      return value
    }else if (value instanceof Array) {
      var newValue = []
      for (let i = 0; i < value.length; ++i) {
        newValue[i] = this.deepCopy(value[i])
      }
      return newValue
    } else if (value instanceof Object) {
      var newValue = {}
      for (let i in value){
        newValue[i] = this.deepCopy(value[i])
      }
      return newValue
    } else {
      return value
    }
  }



  render (){
    return (
      <div>
        <div> 深拷贝,浅拷贝</div>
      </div>
      )
  }
}

export default App;
